const amqp = require('amqplib')
const serverConfig = {
  protocol: 'amqp',
  hostname: '127.0.0.1',
  port: 5672,
  username: 'NxjIOt',
  password: 'Nxj@iot2021',
  vhost:'/VirtualHosts'
}
amqp.connect(serverConfig).then(
  conn => {
    console.log('创建连接成功')
    conn.createChannel().then(
      ch => {
        console.log('创建Channel成功')
        //连接交换机
        ch.assertExchange('api', 'topic',{durable:true}).then(function(ex) {
          //连接队列
          ch.assertQueue("topic").then(function(q) {
            // 交换机bind队列
            //			   队列     交换机     Rounting KEY   arguments
            ch.bindQueue(q.queue, ex.exchange, "topic", {'x-match': 'any'});
            ch.publish(ex.exchange, 'topic', Buffer.from(JSON.stringify(msgObj)));
          })
        })
        // 设置消费者
        ch.consume('topic',
          function(msg) {
            console.log(JSON.parse(msg.content))
          },
          {
            noAck: true
          }
        )
      },
      err => {
        console.log('创建Channel 错误:' + err)
      }
    )
  },
  err => {
    console.log('连接MQ Server 错误:' + err)
  }
)

